Event.observe(window, 'load', function() { CanvasManage.watchManagementFields() }, false);
Event.observe(window, 'load', function() { CanvasManage.watchTitles() }, false);
Event.observe(window, 'load', function() { CanvasManage.initializeButtons() }, false);
Event.observe(window, 'unload', Event.unloadCache, false);

var CanvasManage = {
	
	dbmanage: function(element) {
		if(window.confirm('Are you sure you want to '+element+' Canvas?')) {
		var pars = 'action='+element;
		var target = 'message'
		var url = '../wp-content/plugins/Canvas/ajax/canvas-rescan.php';
		var myAjax = new Ajax.Updater({success: target}, url,
			{method: 'get',
			parameters: pars,
			onComplete: function() { CanvasManage.updateAfterDBChange() }
			});
		}
	},
	
	deleteBlock: function(element) {
		if(window.confirm('Are you sure you want to delete this block?')) {
		var item = 'block_'+element;
		var pars = 'delete='+element;
		var url = '../wp-content/plugins/Canvas/ajax/canvas-management_ajax.php';
		var myAjax = new Ajax.Request(url,
			{method: 'get',
			parameters: pars,
			onComplete: function() { CanvasManage.removeBlock(item) }
			});
		}
	},
	
	duplicateBlock: function(element) {
		var target = 'block_'+element;
		var pars = 'duplicate='+element;
		var url = '../wp-content/plugins/Canvas/ajax/canvas-management_ajax.php';
		var myAjax = new Ajax.Updater({success: target}, url,
			{method: 'get',
			insertion: Insertion.After,
			parameters: pars,
			onComplete: function() { CanvasManage.updateButtons() }
			});
	},
	
	editTitle: function(item) {
		new CanvasAjax.CanvasInPlaceEditor(item, '../wp-content/plugins/Canvas/ajax/canvas-management_ajax.php', {
					callback: function(form, value){ return 'rename=true&id='+item.id+'&value='+escape(value); },
					savingClassName: 'manageSaving'
					});
	},
	
	initializeButtons: function() {
		document.getElementsByClassName('block_info').each(function(item){
			Event.observe(item, 'click', function(){ CanvasManage.toggleBlockInfo(item.id); }, false);
			if($('block_'+item.id).style.display == 'none') new Effect.Appear('block_'+item.id);
		});
		document.getElementsByClassName('delete_block').each(function(item){
			Event.observe(item, 'click', function(){ CanvasManage.deleteBlock(item.id); }, false);
		});
		document.getElementsByClassName('duplicate_block').each(function(item){
			Event.observe(item, 'click', function(){ CanvasManage.duplicateBlock(item.id); }, false);
		});
	},
	
	removeBlock: function(element) {
		new Effect.Fade(element,{ duration: 0.6, afterFinish: function(){ Element.remove(element); CanvasManage.updateCount('-1') } });
	},
	
	resetCount: function() {
		var count = $$('ul.manage li').length;
		count = parseInt(count);
		$('count').firstChild.nodeValue = count;
	},

	sortGroups: function(group) {
		if(group == 'all') {
			$$('ul.manage li').each(function(item){
				$(item).style.display = 'block';
			});
		} else {
			$$('ul.manage li').each(function(item){
				$(item).style.display = 'none';
			});
			$$('ul.manage li.'+group).each(function(item){
				$(item).style.display = 'block';
			});
		}
	},

	toggleBlockInfo: function(element) {
		item = 'info_'+element;
		if($(item).style.display == 'none') {
			new Effect.BlindDown(item,{ duration: 0.4 });
		} else {
			new Effect.BlindUp(item,{ duration: 0.4 });
		}
	},
	
	updateAfterDBChange: function() {
		var target = 'manage';
		var pars = 'update=all';
		var url = '../wp-content/plugins/Canvas/ajax/canvas-management_ajax.php';
		var myAjax = new Ajax.Updater({success: target}, url,
			{method: 'get',
			parameters: pars,
			onComplete: function() { CanvasManage.initializeButtons(); CanvasManage.resetCount(); }
			});
	},

	updateButtons: function() {
		document.getElementsByClassName('delete_block').each(function(item){
			if($('block_'+item.id).style.display == 'none') {
				Event.observe(item, 'click', function(){ CanvasManage.deleteBlock(item.id); }, false);
			}
		});
		document.getElementsByClassName('duplicate_block').each(function(item){
			if($('block_'+item.id).style.display == 'none') {
				Event.observe(item, 'click', function(){ CanvasManage.duplicateBlock(item.id); }, false);
			}
		});
		document.getElementsByClassName('block_info').each(function(item){
			if($('block_'+item.id).style.display == 'none') {
				Event.observe(item, 'click', function(){ CanvasManage.toggleBlockInfo(item.id); }, false);
				new Effect.Appear('block_'+item.id);
			}
		});
		document.getElementsByClassName('title').each(function(item){
			if(item.parentNode.parentNode.style.display == 'none') {
				CanvasManage.editTitle(item);
			}
		});
		updateCount('+1');
	},
	
	updateCount: function(operation) {
		var count = parseInt($('count').firstChild.nodeValue);
		count = eval(count+operation);
		$('count').firstChild.nodeValue = count;
	},
	
	watchManagementFields: function() {
		document.getElementsByClassName('dbmanage').each(function(item){
			Event.observe(item, 'click', function(){ CanvasManage.dbmanage(item.id); }, false);
		});
	},
	
	watchTitles: function() {
		document.getElementsByClassName('title').each(function(item){
			CanvasManage.editTitle(item);
		});
	}
};

// Because Script.aculo.us does some dumb things with backgroundColor
// in the Ajax.InPlaceEditor, we've hacked our own...

CanvasAjax.CanvasInPlaceEditor = Class.create();
CanvasAjax.CanvasInPlaceEditor.prototype = {
  initialize: function(element, url, options) {
    this.url = url;
    this.element = $(element);

    this.options = Object.extend({
      okButton: true,
      okText: "ok",
      cancelLink: true,
      cancelText: "cancel",
      savingText: "Saving...",
      clickToEditText: "Click to edit",
      okText: "ok",
      rows: 1,
      onFailure: function(transport) {
        alert("Error communicating with the server: " + transport.responseText.stripTags());
      },
      callback: function(form) {
        return Form.serialize(form);
      },
      handleLineBreaks: true,
      loadingText: 'Loading...',
      savingClassName: 'inplaceeditor-saving',
      loadingClassName: 'inplaceeditor-loading',
      formClassName: 'inplaceeditor-form',
      externalControl: null,
      submitOnBlur: false,
      ajaxOptions: {},
      evalScripts: false
    }, options || {});

    if(!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + "-inplaceeditor";
      if ($(this.options.formId)) {
        // there's already a form with that name, don't specify an id
        this.options.formId = null;
      }
    }
    
    if (this.options.externalControl) {
      this.options.externalControl = $(this.options.externalControl);
    }
    
    this.element.title = this.options.clickToEditText;
    
    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    Event.observe(this.element, 'click', this.onclickListener);
    Event.observe(this.element, 'mouseover', this.mouseoverListener);
    Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.onclickListener);
      Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    this.onEnterEditMode();
    if (this.options.externalControl) {
      Element.hide(this.options.externalControl);
    }
    Element.hide(this.element);
    this.createForm();
    this.element.parentNode.insertBefore(this.form, this.element);
    Field.scrollFreeActivate(this.editField);
    // stop the event to avoid a page refresh in Safari
    if (evt) {
      Event.stop(evt);
    }
    return false;
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this);

    this.createEditField();

    if (this.options.textarea) {
      var br = document.createElement("br");
      this.form.appendChild(br);
    }

    if (this.options.okButton) {
      okButton = document.createElement("input");
      okButton.type = "submit";
      okButton.value = this.options.okText;
      okButton.className = 'editor_ok_button';
      this.form.appendChild(okButton);
    }

    if (this.options.cancelLink) {
      cancelLink = document.createElement("a");
      cancelLink.href = "#";
      cancelLink.appendChild(document.createTextNode(this.options.cancelText));
      cancelLink.onclick = this.onclickCancel.bind(this);
      cancelLink.className = 'editor_cancel';      
      this.form.appendChild(cancelLink);
    }
  },
  hasHTMLLineBreaks: function(string) {
    if (!this.options.handleLineBreaks) return false;
    return string.match(/<br/i) || string.match(/<p>/i);
  },
  convertHTMLLineBreaks: function(string) {
    return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
  },
  createEditField: function() {
    var text;
    if(this.options.loadTextURL) {
      text = this.options.loadingText;
    } else {
      text = this.getText();
    }

    var obj = this;
    
    if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
      this.options.textarea = false;
      var textField = document.createElement("input");
      textField.obj = this;
      textField.type = "text";
      textField.name = "value";
      textField.value = text;
      textField.className = 'editor_field';
      var size = this.options.size || this.options.cols || 0;
      if (size != 0) textField.size = size;
      if (this.options.submitOnBlur)
        textField.onblur = this.onSubmit.bind(this);
      this.editField = textField;
    } else {
      this.options.textarea = true;
      var textArea = document.createElement("textarea");
      textArea.obj = this;
      textArea.name = "value";
      textArea.value = this.convertHTMLLineBreaks(text);
      textArea.rows = this.options.rows;
      textArea.cols = this.options.cols || 40;
      textArea.className = 'editor_field';      
      if (this.options.submitOnBlur)
        textArea.onblur = this.onSubmit.bind(this);
      this.editField = textArea;
    }
    
    if(this.options.loadTextURL) {
      this.loadExternalText();
    }
    this.form.appendChild(this.editField);
  },
  getText: function() {
    return this.element.innerHTML;
  },
  loadExternalText: function() {
    Element.addClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = true;
    new Ajax.Request(
      this.options.loadTextURL,
      Object.extend({
        asynchronous: true,
        onComplete: this.onLoadedExternalText.bind(this)
      }, this.options.ajaxOptions)
    );
  },
  onLoadedExternalText: function(transport) {
    Element.removeClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = false;
    this.editField.value = transport.responseText.stripTags();
  },
  onclickCancel: function() {
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  onSubmit: function() {

    var form = this.form;
    var value = this.editField.value;
    
    this.onLoading();
    
    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true, 
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          failure: null }, 
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }

    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  },
  onLoading: function() {
    this.saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  showSaving: function() {
    this.oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    Element.addClassName(this.element, this.options.savingClassName);
    Element.show(this.element);
  },
  removeForm: function() {
    if(this.form) {
      if (this.form.parentNode) Element.remove(this.form);
      this.form = null;
    }
  },
  enterHover: function() {
    if (this.saving) return;
    if (this.effect) {
      this.effect.cancel();
    }
    Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
    Element.removeClassName(this.element, this.options.hoverClassName)
    if (this.saving) return;
  },
  leaveEditMode: function() {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    Element.show(this.element);
    if (this.options.externalControl) {
      Element.show(this.options.externalControl);
    }
    this.editing = false;
    this.saving = false;
    this.oldInnerHTML = null;
    this.onLeaveEditMode();
  },
  onComplete: function(transport) {
    this.leaveEditMode();
    if(this.options.onComplete)
	    this.options.onComplete.bind(this)(transport, this.element);
  },
  onEnterEditMode: function() {},
  onLeaveEditMode: function() {},
  dispose: function() {
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
    }
    this.leaveEditMode();
    Event.stopObserving(this.element, 'click', this.onclickListener);
    Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
    Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
      Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
      Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
};
